const { getClientIp } = require('../utils/helpers');
const os = require('os');

class ClientService {
  constructor(chatService) {
    this.chatService = chatService;
    this.clients = new Map();
  }

  registerClient(ws, req) {
    const clientId = getClientIp(req) || this.generateClientId();
    this.clients.set(clientId, { ws, nickname: null, clientId });
    return clientId;
  }

  getClient(clientId) {
    return this.clients.get(clientId);
  }

  handleSetNickname(clientId, nickname) {
    const client = this.getClient(clientId);
    if (!client || client.nickname === nickname) {
      if (client && client.ws.readyState === WebSocket.OPEN) {
        this.chatService.sendSystemMessage(client.ws, '连接成功');
      }
      return;
    }

    if (this.isNicknameTaken(nickname, clientId)) {
      this.chatService.sendSystemMessage(client.ws, '该昵称已被使用，请选择其他昵称');
      return;
    }

    const oldNickname = client.nickname;
    client.nickname = nickname;

    if (oldNickname) {
      this.chatService.broadcastSystemMessage(`${oldNickname} 改名为 ${nickname}`);
      this.chatService.sendSystemMessage(client.ws, '修改昵称成功');
    } else {
      this.chatService.messageService.sendHistory(client.ws);
      this.chatService.broadcastSystemMessage(`${nickname} 加入了聊天室`);
      this.chatService.sendSystemMessage(client.ws, '连接成功');
    }

    this.updateUserList();
  }

  handleClientDisconnect(clientId) {
    const client = this.getClient(clientId);
    if (client?.nickname) {
      this.chatService.broadcastSystemMessage(`${client.nickname} 离开了聊天室`);
    }
    this.clients.delete(clientId);
    this.updateUserList();
  }

  isNicknameTaken(nickname, currentClientId) {
    return Array.from(this.clients.values())
      .some(client => client.nickname === nickname && client.clientId !== currentClientId);
  }

  generateClientId() {
    return Math.random().toString(36).substr(2, 9);
  }

  getUserList() {
    return Array.from(this.clients.values())
      .filter(client => client.nickname)
      .map(client => client.nickname);
  }

  updateUserList() {
    const users = this.getUserList();
    this.chatService.broadcast({
      type: 'userList',
      users: users
    });
  }

  getLocalIP() {
    const interfaces = os.networkInterfaces();
    for (const interfaceName in interfaces) {
      for (const netInterface of interfaces[interfaceName]) {
        if (
          netInterface.family === 'IPv4'
          && !netInterface.internal
          && !interfaceName.startsWith('VMware')
        ) {
          return netInterface.address;
        }
      }
    }
    return null;
  }
}

module.exports = ClientService; 